package Controller;

import java.awt.Graphics2D;
import java.awt.event.ActionEvent;



import java.nio.file.Files;

import static java.nio.file.StandardCopyOption.*;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import View.NewContactView;

/**
 * Action listeners for the JDialog New Contact
 * @author adrien
 *
 */

public class NewContactListener implements ActionListener {
	
	private NewContactView view;
	private AddressBookController controller;
	public static final String NOTHING ="";	
	public static final String ERROR_MESSAGE = "The name tapped is not correct or already used";
	public static final String ERROR_IMG = "The selected file is not an image";
	public static final String SLASH ="/";
	public static final String IMAGE_FOLDER ="/img/";
	public static final String RESOURCES_FOLDER ="resources/";
	public static final String CANCEL ="Cancel";
	public static final String OPEN ="Open";
	public static final String OK ="OK";
	public static final String JPEG_EXTENSION = ".jpeg";
	public static final String JPG_EXTENSION = ".jpg";
	public static final String PNG_EXTENSION = ".png";
	public static final String BMP_EXTENSION = ".bmp";
	public static final String SPACE_ENCODED = "%20";
	public static final String SPACE_CHAR = " ";
	public static final String FILE_BEGINING = "file:/" ;
	public static final String POINT_CHAR = ".";
	public static final String DEFAULT ="Default";
	public static final String DEFAULT_IMG = "default.png";
	
	
	
	private String filePath=null, copyFilePath=null, extension,fileName=null;
	private StringBuilder copyFilePathSB,imageNameSB;
	
	public NewContactListener (NewContactView view, AddressBookController controller) {
		this.view = view;
		this.controller = controller;
	}
	public AddressBookController getController(){
		return controller;
	}
	
	/**
	 * The First name and last name are correct if their are not empty and if there is no space in it
	 *and if a contact with this name doesn't already exist 
	 * @return true if first name and last name are tapped correctly else return false 
	 */
	
	public boolean isTappingCorrect (){
		if (view.getTfFirstName().equals(NOTHING) || view.getTfFirstName().contains(SPACE_CHAR)|| view.getTfLastName().equals(NOTHING)|| view.getTfLastName().contains(SPACE_CHAR) || controller.isContactExist(view.getTfFirstName(), view.getTfLastName())){
			return false;
		}else return true;
	}
	
	
	
	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		
		if (e.getActionCommand().equals(OK)) {
			if (isTappingCorrect()){
				

					if(filePath!=null && copyFilePath!=null){
				
						try {
							Files.copy(Paths.get(filePath), Paths.get(copyFilePath), REPLACE_EXISTING);
						} catch (IOException e1) {
							e1.printStackTrace();
						}
					}
					
					
					if(fileName==null){
						fileName=DEFAULT_IMG;
					}
						
					controller.addContactAction(view.getTfFirstName(),view.getTfLastName(),view.getTfGroup(),view.getTfHomeAddress(),view.getTfCompanyName(),view.getTfCompanyAddress(),view.getTfPersPhone(),view.getTfProPhone(),view.getTfWebSite(),view.getTfEmail(),view.getTfBirthDate(),fileName,new Date());


					
			}
			      
				
				
				

				
				view.dispose();
				
				
				
		}
			
		if (e.getActionCommand().equals(CANCEL)) {
			view.dispose();
		}
		if (e.getActionCommand().equals(OPEN)) {
			//Create a file chooser
			final JFileChooser fc = new JFileChooser();
			int returnVal = fc.showOpenDialog(view);
			
			
			if (returnVal == JFileChooser.APPROVE_OPTION) {
	            
				if (isTappingCorrect()){
					filePath=fc.getSelectedFile().getAbsolutePath();
		            extension = filePath.substring(filePath.lastIndexOf("."));
		            //fileName = filePath.substring(filePath.lastIndexOf("/"));
		            
		            if (extension.equals(JPEG_EXTENSION) || extension.equals(JPG_EXTENSION) || extension.equals(PNG_EXTENSION) || extension.equals(BMP_EXTENSION)){ //filter for the image extensions
		            
		            	copyFilePathSB = new StringBuilder();
		            	copyFilePathSB.append(view.getClass().getResource(RESOURCES_FOLDER)).append(view.getTfFirstName()).append(view.getTfLastName()).append(extension);
		            	copyFilePath = copyFilePathSB.toString();
		            	String copyFilePathSplit []=copyFilePath.split(FILE_BEGINING);
		            	copyFilePath = copyFilePathSplit[1];
		            	copyFilePath=copyFilePath.replace(SPACE_ENCODED, SPACE_CHAR);
		            	fileName = copyFilePath.substring(copyFilePath.lastIndexOf(SLASH) + 1);
		            	
		            	imageNameSB = new StringBuilder();
		            	imageNameSB.append(view.getTfFirstName()).append(view.getTfLastName());
		            	view.setImageName(filePath);
		            	
				        
		            

		            }else {
		            	JOptionPane.showMessageDialog(null,ERROR_IMG);
		            }
				
	            
			}else {
            	JOptionPane.showMessageDialog(null,ERROR_MESSAGE);
            }
			
		}
		
		
	}
		


}
	
}
